﻿#pragma once
#include <QElapsedTimer>
#include <QJsonObject>
#include <PluginObject.h>
#include "RecordLogs_global.h"
#include "../../DatabaseClient/DatabaseWriter.h"

class DatabaseClient;
class QTimer;

enum struct ConnectionState
{
	UnconnectedState = 0,
	ConnectingState = 1,
	ConnectedState =2,
	ClosingState = 3
};

class RecordPlugins : public Plugin
{
	Q_OBJECT
public:
	using Plugin::Plugin;
	virtual ~RecordPlugins() = default;
	QStringView name() const override;
	bool load(QString const& cfgFile = QString()) override;
	void logsEvent(QJsonObject const& logsObj) override;
	void sensorsEvent(QJsonObject const& valuesObj) override;
	QStringList subTopic() const override;
	void handleMessage(QStringView topic, QByteArray payload) override;
	QStringList commands() const override;
private:
	void onWrite();
	void updateConnectionState(QJsonObject const& obj);
	inline void writeCutDur();
	inline void writeRemoteDur();
	inline void writeBootDur();
	inline void writeOilpumpDur();
	inline void writeAutoDur();
private:
	DatabaseWriter* m_dbClient = nullptr;
	QJsonObject m_sensorsValues;
	QTimer* m_timer = nullptr;
	bool m_isCut = false;
	bool m_isRemote = false;
	bool m_isConnected = false;
	bool m_isOilpumpRunning = false;
	bool m_isAutoCut = false;
	QElapsedTimer m_cutTimer;
	QElapsedTimer m_remoteTimer;
	QElapsedTimer m_bootTimer;
	QElapsedTimer m_oilpumpTimer;
	QElapsedTimer m_autoTimer;
	qint64 m_cutElapsed = 0;
	qint64 m_remoteElapsed = 0;
	qint64 m_bootElapsed = 0;
	qint64 m_oilpumpElapsed = 0;
	qint64 m_autoElapsed = 0;
	std::map<QString, std::function<void(QJsonObject const&)>> m_messageMap;
};

